function [ dec_msg ] = msk_dem_viterbi( dat_rx, TREL, tblen, rz_fg )
%

% load data_viterbi_c3b1.mat;
% load msg_c3b1.mat;
% sz_f = 0;

ni = TREL.numInputSymbols;
ns = TREL.numStates;
sps = TREL.OverSampling;
ml = log2(ns);

len_s = length(dat_rx);
len_m = len_s / sps;

dec_msg = NaN(1, len_m);

path_in = NaN(ns, tblen);
path_in1 = NaN(ns, tblen);
wgt_s = zeros(1, ns);
wgt_s1 = zeros(1, ns);
wgt_tp = zeros(1, ni);


cal_st = 1;

dec_cnt = 1;
in_num = ni;
ns_d = 1;
nsc = 1;
for ii=cal_st:1:len_m
    if (ii==1)
        aa = 0;
    end
    
    if (rz_fg && ii==len_m-ml+1)
        in_num = 1;
        ns_d = 2;
    end
    wgt_s1 = -inf * ones(1, ns);
    rx = dat_rx((ii-1)*sps+1:ii*sps);
    
    for jj=1:1:nsc
        stc = jj - 1;
        out = TREL.outputs(:, :, stc+1);
        stn = TREL.nextStates(stc+1,:);
        
        path_len = min(ii, tblen); 
        path_in_tp = path_in(stc+1, 1:path_len-1);
        
        for kk=1:1:in_num
            in = kk - 1;
            if (ii==len_m)
                in = find(stn==0) - 1;
            end
            wgt_tp(in+1) = wgt_s(stc+1) + real(rx * out(in+1,1:sps)');
            if ((wgt_tp(in+1))>(wgt_s1(stn(in+1)+1)))
                wgt_s1(stn(in+1)+1) = wgt_tp(in+1);
                path_in1(stn(in+1)+1, 1:path_len) = [path_in_tp in];
            end 
        end
    end
    nsc = nsc / ns_d;
    
    if (ii<=ml)
        nsc = nsc * 2;
    end
    
    path_in = path_in1;
    wgt_s = wgt_s1;
    if (ii-dec_cnt+1==tblen)
        [path_val, path_num] = max((wgt_s(1:nsc)));
        dec_msg(dec_cnt) = path_in(path_num, 1);
        for jj=1:1:path_len-1
            path_in(:,jj) = path_in(:,jj+1);
        end
        path_in(:,path_len) = -1 * ones(ns, 1);
        dec_cnt = dec_cnt + 1;
    end 
    if (dec_cnt==1)
        aa = 0;
    end
end

dec_msg(dec_cnt:len_m) = path_in(1,1:len_m-dec_cnt+1);


% end

